package com.ecnu.system.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ecnu.common.core.domain.AjaxResult;
import com.ecnu.common.core.domain.HttpCode;
import com.ecnu.common.core.domain.model.LoginUser;
import com.ecnu.common.core.page.PageDomain;
import com.ecnu.common.core.page.TableDataInfo;
import com.ecnu.common.enums.XCNKIType;
import com.ecnu.common.utils.OtherUtil;
import com.ecnu.common.utils.PageUtils;
import com.ecnu.common.utils.StringUtils;
import com.ecnu.common.utils.http.HttpUtils;
import com.ecnu.common.utils.ip.IpUtils;
import com.ecnu.system.domain.SoftwareTool;
import com.ecnu.system.domain.dto.EvaluateListDTO;
import com.ecnu.system.domain.dto.SoftwareDTO;
import com.ecnu.system.domain.vo.SoftwareToolVO;
import com.ecnu.system.mapper.SoftwareToolMapper;
import com.ecnu.system.service.ISoftwareToolService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Service
public class SoftwareToolServiceImpl extends ServiceImpl<SoftwareToolMapper, SoftwareTool> implements ISoftwareToolService {
    @Autowired
    private SoftwareToolMapper softwareToolMapper;

    protected void startPage(PageDomain pageDomain) {
        PageUtils.startPage(pageDomain);
    }

    @Override
    public TableDataInfo getList(EvaluateListDTO dto, LoginUser loginUser) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        LambdaQueryWrapper<SoftwareTool> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getTitle())) {
            wrapper.like(SoftwareTool::getName, dto.getTitle());
        }
        wrapper.eq(SoftwareTool::getDelFlag, "0");
        startPage(dto.getPageDomain());
        List<SoftwareTool> softwareTools = softwareToolMapper.selectList(wrapper);
        List<SoftwareToolVO> copy = new ArrayList<>();
        softwareTools.forEach(softwareTool -> {
            SoftwareToolVO softwareToolVO = new SoftwareToolVO();
            BeanUtils.copyProperties(softwareTool, softwareToolVO);
            softwareToolVO.setId(String.valueOf(softwareTool.getId()));
            copy.add(softwareToolVO);
        });
        return OtherUtil.tableSuccess(copy);
    }

    @Override
    public AjaxResult edit(SoftwareDTO dto, LoginUser loginUser) {
        SoftwareTool tool = new SoftwareTool();
        BeanUtils.copyProperties(dto, tool);
        Boolean status = null;
        if (StringUtils.isBlank(dto.getId())) {
            status = save(tool);
        } else  {
            tool.setId(Integer.valueOf(dto.getId()));
            status = updateById(tool);
        }
        return status ? AjaxResult.success("保存成功") : AjaxResult.error("保存失败");
    }

    @Override
    public TableDataInfo getListForUser(EvaluateListDTO dto, LoginUser loginUser) throws InvocationTargetException, NoSuchMethodException, InstantiationException, IllegalAccessException {
        LambdaQueryWrapper<SoftwareTool> wrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(dto.getTitle())) {
            wrapper.like(SoftwareTool::getName, dto.getTitle());
        }
        wrapper.eq(SoftwareTool::getDelFlag, "0");
        wrapper.eq(SoftwareTool::getStatus, "1");
        startPage(dto.getPageDomain());
        List<SoftwareTool> softwareTools = softwareToolMapper.selectList(wrapper);
        List<SoftwareToolVO> copy = new ArrayList<>();
        softwareTools.forEach(softwareTool -> {
            SoftwareToolVO softwareToolVO = new SoftwareToolVO();
            BeanUtils.copyProperties(softwareTool, softwareToolVO);
            softwareToolVO.setId(String.valueOf(softwareTool.getId()));
            if (softwareTool.getUrl().contains("//x.cnki.net")) {//现阶段调整cnki研学的接口
                try {
                    XCnki(softwareToolVO,loginUser);
                } catch (UnsupportedEncodingException e) {
                    throw new RuntimeException(e);
                }
            }
            copy.add(softwareToolVO);
        });
        return OtherUtil.tableSuccess(copy);
    }

    private void XCnki(SoftwareToolVO softwareTool, LoginUser loginUser) throws UnsupportedEncodingException {
        String strings = softwareToolMapper.selectMenu_("116");//获取软件工具菜单的相对地址
        if (StringUtils.isNotBlank(strings)) {
            String extracted = extracted(softwareTool.getUrl(), loginUser.getUserId(), strings);//后续改成工具地址
            softwareTool.setUrl(extracted);
        }
    }
    public String extracted(String title, Long userId, String targetUrl) throws UnsupportedEncodingException {

        //取token
        String url = "https://my.cnki.net/IntegrateLogin/api/IntegrateLoginApi/UserLogin";
        String ipAddr = IpUtils.getIpAddr();
        //包装参数
        HashMap<String, String> map = new HashMap<>();
        map.put(XCNKIType.Key.getCode(), XCNKIType.Key.getInfo());//学校秘钥
        map.put(XCNKIType.UserName.getCode(), XCNKIType.UserName.getInfo());//学校名称
        map.put("SubUserName", String.valueOf(userId));//登录用户id
        map.put("UserIp", ipAddr);//用户客户端ip
        String jsonString = JSON.toJSONString(map);
        String contentType = "application/json";
        //获取token
        String token = HttpUtils.sendPost(url, jsonString, contentType,new HashMap<>());
        if (StringUtils.isBlank(token)) {
            return title;
        }
        HttpCode httpCode = JSON.parseObject(token, HttpCode.class);
        if (httpCode.getCode().equals("0")) {
            log.error("知网研学获取token失败:"+httpCode.getMessage());
            return title;
        }
        //获取aamsApi的jwt
        String jwt = OtherUtil.getJwt(ipAddr);
        //读取用户信息
        String xcnkiUser =OtherUtil.selectXCNKIUser(jwt, httpCode.getToken());
        //用户未绑定的情况跳转登录地址设为学习中心平台
        if (StringUtils.isBlank(xcnkiUser)) {
            title="https://ba.ecnu.edu.cn"+targetUrl+"/list";
        }else {
            //有对接上的话添加团队
            OtherUtil.InstantTeam(xcnkiUser, jwt);
        }
        String geturl="https://my.cnki.net/IntegrateLogin/Redirect/Index?token="+httpCode.getToken()
                +"&SubUserName="+userId+"&ReturnUrl="+ URLEncoder.encode(title,"UTF-8");

        return geturl;
    }
}
